import Request from './request'
import qs from 'qs'
import { getToken, removeToken } from '@utils/storage.js'
import { message } from "ant-design-vue";
import router from "@/router/index.js";

const contentType = {
  form: 'application/x-www-form-urlencoded;charset=UTF-8',
  json: 'application/json;charset=UTF-8',
}

export let apiBaseUrl = import.meta.env.VITE_API_BASE_URL;

const request = new Request({
  baseURL: apiBaseUrl,
  timeout: 40000,
  interceptors: {
    // 请求拦截器
    requestInterceptors: (config) => {
      const token = getToken()
      if (config.url === '/loginQueryType') {
        //準備加標識特殊處理
      } else {
        if (token && config.url !== '/login') {
          config.headers['X-Access-Token'] = token
        }
      }
      if (config.params) {
        config.params = {
          _t: (Date.parse(new Date()) / 1000),
          ...config.params
        }
      }
      if (config.options) {
        const { type, headers } = config.options;
        if (type) {
          config.headers['content-type'] = contentType[type];
          if (type == 'form') {
            config.data = qs.stringify(config.data);
          }
        }
        if (headers) {
          Object.keys(headers).forEach(key => {
            config.headers[key] = headers[key];
          })
          delete config.options.headers
        }
        config = { ...config, ...config.options }
      }
      return config
    },
    // 响应拦截器
    responseInterceptors: (result) => {
      return result
    },
    responseInterceptorsCatch: (error) => {
      if (error.message === 'Network Error') {
        return message.error('Network Error')
      }
      const response = error.response
      if (response.data.code == 401) {
        message.error('token无效，请重新登录')
        removeToken(import.meta.env.VITE_TOKEN)
        router.push({ path: '/login', replace: true })
      }
      return response.data
    }
  },
})

/**
 * @descriptions: 函数的描述
 * @generic D 请求参数
 * @generic T 响应结构
 * @param {SSORequestConfig} config 不管是GET还是POST请求都使用data
 * @returns {Promise}
 */
const ssoRequest = (config) => {
  const { method = 'GET', responseType } = config
  if (method === 'get' || method === 'GET' || method === 'delete' || method === 'DELETE') {
    config.params = config.data
  }

  if (responseType === 'blob') {
    config['content-type'] = 'application/json;charset=UTF-8'
  }
  // else{
  //   if(method === 'get'){
  //     let {params} = config
  //     if(params){
  //       for (const datum in params) {
  //         params[datum] = params[datum].toString().trim()
  //       }
  //     }
  //   }else if(method === 'post' || method === 'POST'){

  //     if(config.data && Object.keys(config.data).length !== 0){
  //       let {data} = config
  //       if(data){
  //         for (const datum in data) {
  //           data[datum] = data[datum].toString().trim()
  //         }
  //       }
  //     }

  //   }
  // }


  return request.request(config)
}
//  取消请求
export const cancelRequest = (url) => {
  return request.cancelRequest(url)
}
// 取消全部请求
export const cancelAllRequest = () => {
  return request.cancelAllRequest()



}

export function commGet({ url, method, data, options = {} }) {
  return ssoRequest({
    url, method, data
  }).then((res) => {
    return Promise.resolve(res)
  }).catch((r) => {
    console.log('e', r)
    return Promise.reject(r)
  })
}

export const postFile = (url, method, data, name) => {
  console.log('data',data)
  return ssoRequest({
    url, method, data, responseType: 'blob'
  }).then((res) => {
    if (res.size === 0) {
      return message.success('上传成功')
    }
    let url = window.URL.createObjectURL(new Blob([res]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', name)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) //下载完成移除元素
    window.URL.revokeObjectURL(url) //释放掉blob对象
    return Promise.resolve('有异常数据')
  }).catch((r) => {
    console.log('r',r)
    return Promise.reject(r)
  })
}
export const importFile = (url, method, data, name) => {
  return ssoRequest({
    url, method, data, responseType: 'blob'
  }).then((res) => {
    return message.success('导入成功')
  }).catch((r) => {
    return Promise.reject(r)
  })
}
export function commPut({ url, method, data, options = {} }) {
  return ssoRequest({
    url: url, method: method, data: data
  }).then((res) => {
    return Promise.resolve(res)
  }).catch((r) => {
    return Promise.reject(r)
  })
}

export function commPost({ url, method, data }) {
  return ssoRequest({
    url: url, method: method, data: data
  }).then((res) => {
    return Promise.resolve(res)
  }).catch((r) => {
    return Promise.reject(r)
  })
}

export function deleteAction({ url, method, data }) {
  return ssoRequest({
    url: url,
    method: 'delete',
    data
  })
}
export function downFile(url, data, options = {}, method = 'get') {
  return ssoRequest({
    url: url,
    method,
    data,
    responseType: 'blob'
  })
}


export default ssoRequest
